import { h, Fragment } from "preact";
import { Handlers, PageProps } from "$fresh/server.ts";
import { Post, getDbClient } from "../../../utils/db.ts";
import HeadComponent from "../../../components/Head.tsx";
import Button from "../../../components/Button.tsx";
import { AdminState } from "../../_middleware.ts";
import Pagination from "../../../components/Pagination.tsx";

interface AdminPostsData {
  posts: Post[];
  totalPosts: number;
  currentPage: number;
  totalPages: number;
  showDeleteSuccessMessage?: boolean;
}

export const handler: Handlers<AdminPostsData, AdminState> = {
  async GET(req, ctx) {
    if (!ctx.state.isAdmin) {
      const headers = new Headers();
      headers.set("location", "/admin/login?redirect=/admin/posts");
      return new Response(null, { status: 303, headers });
    }

    const url = new URL(req.url);
    const page = parseInt(url.searchParams.get("page") || "1");
    const pageSize = 10; // Number of posts per page
    const showDeleteSuccessMessage = url.searchParams.get("deleted") === "true";
    const offset = (page - 1) * pageSize;

    let client;
    try {
      client = await getDbClient();
      const countResult = await client.query("SELECT COUNT(*) as count FROM posts");
      const totalPosts = (countResult[0] as { count: number }).count;
      const totalPages = Math.ceil(totalPosts / pageSize);

      const postsResult = await client.query(
        "SELECT id, title, content, created_at FROM posts ORDER BY created_at DESC LIMIT ? OFFSET ?",
        [pageSize, offset]
      );
      const posts = postsResult as Post[];

      return ctx.render({
        posts,
        totalPosts,
        currentPage: page,
        totalPages,
        showDeleteSuccessMessage
      });
    } catch (error) {
      console.error("Error fetching posts for admin:", error);
      return ctx.render({
        posts: [],
        totalPosts: 0,
        currentPage: 1,
        totalPages: 0,
        showDeleteSuccessMessage: false
      });
    } finally {
      if (client) await client.close();
    }
  },
};

export default function AdminPostsIndexPage({ data, state }: PageProps<AdminPostsData, AdminState>) {
  const { posts, totalPosts, currentPage, totalPages, showDeleteSuccessMessage } = data;
  const { isAdmin, adminNickname, adminAvatarUrl } = state;

  const formatDate = (dateStr: string | Date) => {
    const date = new Date(dateStr);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  return (
    <>
      <HeadComponent title="管理文章" description="管理所有博客文章">
        <link rel="stylesheet" href="/styles.css" />
        <link rel="stylesheet" href="/article-styles.css" />
      </HeadComponent>

      <div class="article-container flex flex-col min-h-screen">
        <header class="article-header-glass sticky top-0 z-50">
          <div class="container mx-auto max-w-5xl py-3 px-4 md:px-0 flex items-center justify-between">
            <a href="/" class="flex items-center space-x-2 text-gray-600 hover:text-blue-600 transition-colors duration-200">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                <path stroke-linecap="round" stroke-linejoin="round" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
              </svg>
              <span class="text-sm font-medium">返回首页</span>
            </a>
            <div class="flex items-center gap-4">
                <h1 class="text-xl font-semibold text-gray-700">文章管理</h1>
                {isAdmin && adminNickname && (
                    <div class="flex items-center gap-3">
                      {adminAvatarUrl && adminAvatarUrl.trim() !== "" ? (
                        <img src={adminAvatarUrl} alt={adminNickname} class="w-7 h-7 rounded-full object-cover border border-gray-300 shadow-sm" />
                      ) : (
                        <div class="w-7 h-7 rounded-full bg-slate-200 flex items-center justify-center text-xs font-bold text-slate-500 border border-slate-300 shadow-sm">
                          {adminNickname.charAt(0).toUpperCase()}
                        </div>
                      )}
                      <a href="/api/auth/logout" class="text-sm text-gray-700 font-medium hover:text-blue-700 hover:underline cursor-pointer" title="点击退出登录">
                        你好, {adminNickname}
                      </a>
                    </div>
                )}
                {isAdmin && !adminNickname && (
                    <div class="flex items-center gap-3">
                        <div class="w-7 h-7 rounded-full bg-slate-200 flex items-center justify-center text-gray-500 border border-slate-300 shadow-sm">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd" />
                            </svg>
                        </div>
                        <a href="/api/auth/logout" class="text-xs text-blue-600 hover:text-blue-800 hover:underline">退出登录</a>
                    </div>
                )}
            </div>
            <Button href="/admin/posts/new" variant="primary" size="sm" className="bg-[#7b5e4d] hover:bg-[#6a5040] text-white">
              撰写新文章
            </Button>
          </div>
        </header>

        <main class="flex-grow py-8 md:py-10 px-4 md:px-0">
          <div class="container mx-auto max-w-5xl">
            {showDeleteSuccessMessage && (
              <div class="mb-6 px-6 py-3 bg-red-50 text-red-700 text-sm rounded-lg border border-red-200">
                文章已成功删除。
              </div>
            )}

            {posts.length === 0 ? (
              <div class="text-center py-16">
                <div class="text-5xl mb-6 text-gray-300 mx-auto">📝</div>
                <h2 class="text-xl font-medium text-gray-700 mb-3">暂无文章</h2>
                <p class="text-gray-500 mb-6">您还没有创建任何文章。</p>
                <Button href="/admin/posts/new" variant="primary">
                  立即创建第一篇
                </Button>
              </div>
            ) : (
              <div class="bg-white shadow-subtle rounded-lg overflow-hidden">
                <table class="min-w-full divide-y divide-gray-200">
                  <thead class="bg-gray-50">
                    <tr>
                      <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                      <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">标题</th>
                      <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建日期</th>
                      <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                    </tr>
                  </thead>
                  <tbody class="bg-white divide-y divide-gray-200">
                    {posts.map((post) => (
                      <tr key={post.id}>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{post.id}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                          <a href={`/posts/${post.id}`} target="_blank" class="hover:text-blue-600" title="查看文章">
                            {post.title}
                          </a>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{formatDate(post.created_at)}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium space-x-2">
                          <a href={`/admin/posts/${post.id}/edit`} class="text-indigo-600 hover:text-indigo-900">编辑</a>
                          <form
                            method="POST"
                            action="/api/posts/delete"
                            onSubmit={(e) => { if (!confirm('确定要删除这篇文章吗？操作不可撤销。')) e.preventDefault(); }}
                            class="inline"
                          >
                            <input type="hidden" name="post_id" value={post.id.toString()} />
                            <button type="submit" class="text-red-600 hover:text-red-900">删除</button>
                          </form>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
            {totalPages > 1 && (
                <div class="mt-8">
                    <Pagination
                        currentPage={currentPage}
                        totalPages={totalPages}
                    />
                </div>
            )}
          </div>
        </main>

        <footer class="article-footer-glass py-8 mt-auto">
          <div class="container mx-auto max-w-5xl px-4 md:px-0">
            <p class="text-xs text-gray-500 text-center">
              © {new Date().getFullYear()} MiniBlog 管理后台.
            </p>
          </div>
        </footer>
      </div>
    </>
  );
} 